package com.example.interceptor.demos.config;

import com.example.interceptor.demos.common.ResultAjax;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * Created with Intellij IDEA.
 * Description;
 * User:TQ02
 * Data:2023-12-04
 * Time:22:05
 * Text：返回值的保底实现类
 */
@ControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice {

    @Autowired
    private ObjectMapper objectMapper;

    //开启重写
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
//       保底策略

//        方法一：但是面临String方法时，会报错，返回的是Json格式，因此我们需要类型转换
//        if(body instanceof ResultAjax){
//             return body;
//         }
//        return ResultAjax.succ(body);

        if(body instanceof ResultAjax){
            return body;
        }
        if(body instanceof String){
            ResultAjax resultAjax=ResultAjax.succ(body);//json转换为String
                try {
                    return objectMapper.writeValueAsString(resultAjax);
                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }
            }

        return ResultAjax.succ(body);
    }
}
